package com.junjie.springcloud.controller;

import com.junjie.springcloud.entities.CommonResult;
import com.junjie.springcloud.entities.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
@Slf4j
public class OrderController {
    //远程调用的 地址 (问题：这里注册了之后为什么不能用了)
    //public static final String PAYMENY_URL = "http://localhost:8001";
    public static final String PAYMENY_URL = "http://CLOUD-PAYMENT-SERVICE";

    //这里还可以用 Inject
    @Resource
    private RestTemplate restTemplate;

    @PostMapping("customer/payment/create")
    public CommonResult<Payment> create(Payment payment){
        /**
         param1 请求地址，param2 请求参数， param3 返回类型
         */
        return restTemplate.postForObject(PAYMENY_URL + "/payment/create", payment, CommonResult.class);
    }

    @GetMapping("customer/payment/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id")Long id){
        return restTemplate.getForObject(PAYMENY_URL + "/payment/" + id, CommonResult.class);
    }

    @GetMapping("customer/payment/getForEntity/{id}")
    public CommonResult<Payment> getPaymentById1(@PathVariable("id")Long id){
        ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENY_URL + "/payment/" + id, CommonResult.class);
        if(entity.getStatusCode().is2xxSuccessful()) {
            log.info(entity.getStatusCode() + "\t" + entity.getHeaders());
            return entity.getBody();
        } else {
            return new CommonResult<>(444, "操作失败");
        }
    }

    // zipkin 的测试
    @GetMapping("customer/payment/zipkin")
    public String getZipkin(){
        return restTemplate.getForObject(PAYMENY_URL + "/payment/zipkin" , String.class);
    }
}
